<template>
  <!-- 外层框架 - 添加点击事件监听 -->
  <view class="iphone-frame" :class="{ 'light-theme': isLightTheme }" @click="handleBackgroundClick">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <!-- 顶部安全区域占位 -->
      <view class="safe-top"></view>

      <view class="nav-content">
        <view class="nav-left">
          <view class="theme-toggle" @click.stop="toggleTheme">
            <view class="icon theme-icon"></view>
            <!-- 将emoji替换为图片标签 -->
            <image v-if="isLightTheme" src="/static/images/taiyang.png" class="theme-icon-image" mode="aspectFill"></image>
            <image v-else src="/static/images/yueliang.png" class="theme-icon-image" mode="aspectFill"></image>
          </view>
        </view>
        <view class="nav-center">
          <view class="icon nav-icon"></view>
          <text>灶搭子</text>
        </view>
        <view class="nav-right">
          <view class="icon user-icon"></view>
        </view>
      </view>
    </view>

    <!-- 主体滚动区 -->
    <scroll-view class="content" scroll-y @click.stop="handleContentClick">
      <view class="section">
        <!-- 标题 -->
        <view class="section-header">
          <view class="section-title short-underline">
            <image src="/static/images/xilanhua1.png" class="image-icon" mode="aspectFill"></image>
            <text>无论生活多苦记得照顾好自己</text>
          </view>
          <view class="section-subtitle">
            <text>选择您家里有的食材，我来帮您搭配菜谱~</text>
          </view>
        </view>

        <!-- 蔬菜 -->
        <view class="group vegetable-group">
          <div class="group-decoration"></div>
          <view class="group-title">
            <image src="/static/images/xilanhua1.png" class="image-icon" mode="aspectFill"></image>
            <text>菜菜们</text>
          </view>
          <view class="tag-list">
            <view v-for="item in vegetables" :key="item.name"
              :class="['tag', item.active ? 'tag-active' : 'tag-inactive']" @click="toggle(item)">
              <image :src="item.icon" class="image-icon-small" mode="aspectFill"></image>
              <text>{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 肉类 -->
        <view class="group meat-group">
          <div class="group-decoration"></div>
          <view class="group-title">
            <image src="/static/images/yz-rougucha.png" class="image-icon" mode="aspectFill"></image>
            <text>肉肉们</text>
          </view>
          <view class="tag-list">
            <view v-for="item in meats" :key="item.name"
              :class="['tag', item.active ? 'meat-tag-active' : 'meat-tag-inactive']" @click="toggle(item)">
              <image :src="item.icon" class="image-icon-small" mode="aspectFill"></image>
              <text>{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 主食 -->
        <view class="group staple-group">
          <div class="group-decoration"></div>
          <view class="group-title">
            <image src="/static/images/mifan.png" class="image-icon" mode="aspectFill"></image>
            <text>来点主食？(不选也行)</text>
          </view>
          <view class="tag-list">
            <view v-for="item in staples" :key="item.name"
              :class="['tag', item.active ? 'staple-tag-active' : 'staple-tag-inactive']" @click="toggle(item)">
              <image :src="item.icon" class="image-icon-small" mode="aspectFill"></image>
              <text>{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 厨具 -->
        <view class="group tool-group">
          <div class="group-decoration"></div>
          <view class="group-title">
            <image src="/static/images/canchugongju.png" class="image-icon" mode="aspectFill"></image>
            <text>再选一下厨具</text>
          </view>
          <view class="tag-list">
            <view v-for="item in tools" :key="item.name"
              :class="['tag', item.active ? 'tool-tag-active' : 'tool-tag-inactive']" @click="toggle(item)">
              <image :src="item.icon" class="image-icon-small" mode="aspectFill"></image>
              <text>{{ item.name }}</text>
            </view>
          </view>
          
          <!-- 添加匹配模式选择 -->
          <view class="match-mode-section">
            <view class="group-title">
              <text>选择匹配模式</text>
            </view>
            <view class="mode-list">
              <view :class="['mode-button', matchMode === 'loose' ? 'mode-button-active' : '']" @click="setMatchMode('loose')">
                <text>模糊匹配</text>
              </view>
              <view :class="['mode-button', matchMode === 'strict' ? 'mode-button-active' : '']" @click="setMatchMode('strict')">
                <text>严格匹配</text>
              </view>
              <view :class="['mode-button', matchMode === 'survival' ? 'mode-button-active' : '']" @click="setMatchMode('survival')">
                <text>生存模式</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 其他内容区域 -->

        <!-- 菜谱结果 -->
        <view class="section-title short-underline">
          <!-- <image src="/static/images/yz-rougucha.png" class="image-icon" mode="aspectFill"></image> -->
          <text>看看您今天吃啥</text>
        </view>
        <RecipeResults :recipes="recipes" :is-light-theme="isLightTheme" />
      </view>
    </scroll-view>

    <!-- 扇形菜单 - 添加.stop阻止冒泡 -->
    <view class="fan-menu" @click.stop="handleFanMenuClick">
      <!-- 主按钮 -->
      <view class="fan-main-button" :class="{ 'open': isFanMenuOpen }" @click="toggleFanMenu">
        <image src="/static/images/candan.png" class="fan-button-icon" mode="aspectFill"></image>
      </view>

      <!-- 子按钮：搜索 -->
      <view class="fan-sub-button fan-sub-button-1" :class="{ 'open': isFanMenuOpen }" @click="handleSearch">
        <image src="/static/images/shenhesousuo.png" class="fan-button-icon" mode="aspectFill"></image>
      </view>
      
      <!-- 子按钮：主题切换 -->
      <view class="fan-sub-button fan-sub-button-2" :class="{ 'open': isFanMenuOpen }" @click="handleThemeToggle">
        <image :src="isLightTheme ? '/static/images/taiyang.png' : '/static/images/yueliang.png'" class="fan-button-icon" mode="aspectFill"></image>
      </view>
      
      <!-- 子按钮：反馈 -->
      <button class="fan-sub-button fan-sub-button-3" :class="{ 'open': isFanMenuOpen }" open-type="contact" @tap.stop="toggleFanMenu">
        <image src="/static/images/fankuiA.png" class="fan-button-icon" mode="aspectFill"></image>
      </button>
      
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, defineOptions } from 'vue';
import RecipeResults from '/components/RecipeResults.vue';

// 主题状态
const isLightTheme = ref(false)
// 添加模式状态，默认选择模糊匹配
const matchMode = ref('loose') // 'loose', 'strict', 'survival'
// 扇形菜单状态
const isFanMenuOpen = ref(false)

// 导入食材图标映射
import foodIcons from '/types/foodIcons.json'

// 获取菜谱第一个食材对应的图标
// 修改getRecipeIcon函数
const getRecipeIcon = (recipe) => {
  if (!recipe || !recipe.stuff) {
    return ['/static/images/yz-rougucha.png']; // 返回包含默认图标的数组
  }
  
  // 分割食材字符串
  const stuffs = recipe.stuff.split(',').map(s => s.trim());
  
  // 查找所有在foodIcons中存在的食材图标，并限制最多显示3个
  const matchingIcons = stuffs
    .map(stuff => foodIcons[stuff])
    .filter(icon => icon !== undefined)
    .slice(0, 3); // 添加这行代码，限制最多3个图标
  
  // 如果没有找到匹配的食材图标，返回默认图标数组
  return matchingIcons.length > 0 ? matchingIcons : ['/static/images/yz-rougucha.png'];
}

// 蔬菜 - 修复icon路径
const vegetables = reactive([
  { name: '土豆', active: false, icon: '/static/images/tudou1.png' },
  { name: '胡萝卜', active: false, icon: '/static/images/huluobu1.png' },
  { name: '花菜', active: false, icon: '/static/images/huacai-.png' },
  { name: '番茄', active: false, icon: '/static/images/xihongshi1.png' },
  { name: '白萝卜', active: false, icon: '/static/images/bailuobu.png' },
  { name: '西葫芦', active: false, icon: '/static/images/xihulu1.png' },
  { name: '芹菜', active: false, icon: '/static/images/shucai-1.png' },
  { name: '黄瓜', active: false, icon: '/static/images/huanggua1.png' },
  { name: '洋葱', active: false, icon: '/static/images/yangcong1.png' },
  { name: '莴笋', active: false, icon: '/static/images/shucai-.png' },
  { name: '菌菇', active: false, icon: '/static/images/mogu.png' },
  { name: '茄子', active: false, icon: '/static/images/qiezi1.png' },
  { name: '豆腐', active: false, icon: '/static/images/doufu.png' },
  { name: '包菜', active: false, icon: '/static/images/baocai.png' },
  { name: "白菜", active: false, icon: '/static/images/dabaicai1.png' },
])
// 肉类 - 修复icon路径
const meats = reactive([
  { name: '午餐肉', active: false, icon: '/static/images/rou.png' },
  { name: '香肠', active: false, icon: '/static/images/xiangchang.png' },
  { name: '腊肠', active: false, icon: '/static/images/lachang.png' },
  { name: '鸡肉', active: false, icon: '/static/images/jitui.png' },
  { name: '猪肉', active: false, icon: '/static/images/yz-rougucha.png' },
  { name: '鸡蛋', active: false, icon: '/static/images/jidan.png' },
  { name: '虾', active: false, icon: '/static/images/xia.png' },
  { name: '牛肉', active: false, icon: '/static/images/rou.png' },
  { name: '骨头', active: false, icon: '/static/images/gutou.png' },
])
// 主食 - 修复icon路径
const staples = reactive([
  { name: '面食', active: false, icon: '/static/images/mianshi.png' },
  { name: '面包', active: false, icon: '/static/images/mianbao.png' },
  { name: '米', active: false, icon: '/static/images/mifan.png' },
  { name: '方便面', active: false, icon: '/static/images/paomian.png' }
])
// 厨具 - 修复icon路径
const tools = reactive([
  { name: '烤箱', active: false, icon: '/static/images/kaoxiang.png' },
  { name: '空气炸锅', active: false, icon: '/static/images/kongqizhaguo.png' },
  { name: '微波炉', active: false, icon: '/static/images/sekuaiweibolu.png' },
  { name: '电饭煲', active: false, icon: '/static/images/dianfanbao.png' },
  { name: '一口能炒又能煮的大锅', active: false, icon: '/static/images/feiteng.png' }
])
// 菜谱（初始静态数据）
const recipes = reactive([])
// 导入菜谱数据
import recipeData from '/static/data/recipe.json'

function toggle(item) {
  // 检查当前项是否属于厨具数组
  const isToolItem = tools.includes(item);

  if (isToolItem) {
    // 如果是厨具，先将所有其他厨具的active状态设为false
    tools.forEach(tool => {
      if (tool !== item) {
        tool.active = false;
      }
    });
  }

  // 切换当前项的active状态
  item.active = !item.active;

  // 根据活跃食材匹配菜谱
  matchRecipesBySelectedStuffs();
}

// 切换匹配模式
function setMatchMode(mode) {
  matchMode.value = mode;
  matchRecipesBySelectedStuffs(); // 切换模式后重新匹配
}

function matchRecipesBySelectedStuffs() {
  // 获取所有活跃的食材名称
  const selectedStuffs = [];
  
  // 添加活跃的蔬菜
  vegetables.forEach(vegetable => {
    if (vegetable.active) {
      selectedStuffs.push(vegetable.name);
    }
  });
  
  // 添加活跃的肉类
  meats.forEach(meat => {
    if (meat.active) {
      selectedStuffs.push(meat.name);
    }
  });
  
  // 添加活跃的主食
  staples.forEach(staple => {
    if (staple.active) {
      selectedStuffs.push(staple.name);
    }
  });
  
  // 获取选中的厨具并处理特殊情况
  const selectedToolItem = tools.find(tool => tool.active);
  let selectedTool = selectedToolItem?.name;
  
  // 当选择"一口能炒又能煮的大锅"时转为"一口大锅"进行搜索
  if (selectedTool === '一口能炒又能煮的大锅') {
    selectedTool = '一口大锅';
  }
  
  // 清空当前菜谱列表
  recipes.splice(0, recipes.length);
  
  // 如果没有选择任何东西，不进行匹配
  if (selectedStuffs.length === 0 && !selectedTool) {
    return;
  }
  
  // 定义显示的菜谱函数
  const displayRecipes = function() {
    switch (matchMode.value) {
      case 'strict':
        return recipeData.filter((item) => {
          const stuffFlag = selectedStuffs.every(stuff => {
            const recipeStuffs = item.stuff.split(',').map(s => s.trim());
            return recipeStuffs.includes(stuff);
          });
          const toolFlag = () => {
            if (!selectedTool) return true;
            return item.tools.includes(selectedTool) || 
                   (selectedTool.includes('大锅') && item.tools.includes('大锅')) ||
                   (selectedTool.includes('烤箱') && item.tools.includes('烤箱')) ||
                   (selectedTool.includes('空气炸锅') && item.tools.includes('空气炸锅')) ||
                   (selectedTool.includes('微波炉') && item.tools.includes('微波炉')) ||
                   (selectedTool.includes('电饭煲') && item.tools.includes('电饭煲'));
          };
          return selectedTool ? stuffFlag && toolFlag() : stuffFlag;
        });
      case 'loose':
        return recipeData.filter((item) => {
          const stuffFlag = selectedStuffs.some(stuff => {
            const recipeStuffs = item.stuff.split(',').map(s => s.trim());
            return recipeStuffs.includes(stuff);
          });
          const toolFlag = () => {
            if (!selectedTool) return true;
            return item.tools.includes(selectedTool) || 
                   (selectedTool.includes('大锅') && item.tools.includes('大锅')) ||
                   (selectedTool.includes('烤箱') && item.tools.includes('烤箱')) ||
                   (selectedTool.includes('空气炸锅') && item.tools.includes('空气炸锅')) ||
                   (selectedTool.includes('微波炉') && item.tools.includes('微波炉')) ||
                   (selectedTool.includes('电饭煲') && item.tools.includes('电饭煲'));
          };
          // 同时存在厨具和材料，则同时判断
          if (selectedTool && selectedStuffs.length) {
            return stuffFlag && toolFlag();
          } else {
            if (selectedStuffs.length) 
              return stuffFlag;
            else if (selectedTool) 
              return toolFlag();
            return false;
          }
        });
      case 'survival':
        return recipeData.filter((item) => {
          const stuffFlag = () => {
            const recipeStuffs = item.stuff.split(',').map(s => s.trim());
            return recipeStuffs.every(stuff => selectedStuffs.includes(stuff));
          };
          const toolFlag = () => {
            if (!selectedTool) return true;
            return item.tools.includes(selectedTool) || 
                   (selectedTool.includes('大锅') && item.tools.includes('大锅')) ||
                   (selectedTool.includes('烤箱') && item.tools.includes('烤箱')) ||
                   (selectedTool.includes('空气炸锅') && item.tools.includes('空气炸锅')) ||
                   (selectedTool.includes('微波炉') && item.tools.includes('微波炉')) ||
                   (selectedTool.includes('电饭煲') && item.tools.includes('电饭煲'));
          };
          return selectedTool ? stuffFlag() && toolFlag() : stuffFlag();
        });
      default:
        return [];
    }
  };
  
  // 获取匹配的菜谱并添加到列表
  const matchedRecipes = displayRecipes();
  matchedRecipes.forEach(recipe => {
    recipes.push(recipe);
  });
}

// 修改切换主题函数，实现用户手动切换并保存到本地
function toggleTheme() {
  isLightTheme.value = !isLightTheme.value;
  // 保存用户的主题偏好到本地存储
  uni.setStorageSync('theme', isLightTheme.value ? 'light' : 'dark');
}

// 初始化主题函数
function initTheme() {
  // 先检查本地是否有用户保存的主题偏好
  const savedTheme = uni.getStorageSync('theme');
  
  if (savedTheme) {
    // 如果有保存的主题，使用保存的主题
    isLightTheme.value = savedTheme === 'light';
  } else {
    // 如果没有保存的主题，根据当前时间设置主题
    const now = new Date();
    const hour = now.getHours();
    // 早上6点到下午6点显示白天主题，其他时间显示黑夜主题
    isLightTheme.value = hour >= 6 && hour < 18;
  }
}

// 扇形菜单相关函数
function toggleFanMenu() {
  isFanMenuOpen.value = !isFanMenuOpen.value;
}

function handleThemeToggle() {
  toggleTheme();
  toggleFanMenu(); // 点击后关闭菜单
}


function handleSearch() {
  // 搜索功能实现
  // uni.showToast({
  //   title: '搜索功能开发中...',
  //   icon: 'none'
  // });
  uni.navigateTo({
    url: '/pages/search/search'
  });
  toggleFanMenu(); // 点击后关闭菜单
}

// 新增：处理背景点击事件，关闭菜单
function handleBackgroundClick() {
  if (isFanMenuOpen.value) {
    isFanMenuOpen.value = false;
  }
}

// 新增：处理内容区域点击事件，关闭菜单
function handleContentClick() {
  if (isFanMenuOpen.value) {
    isFanMenuOpen.value = false;
  }
}

// 新增：处理菜单区域点击事件，防止冒泡
function handleFanMenuClick() {
  // 空函数，仅用于阻止事件冒泡
}

// 使用defineOptions配置页面级选项
defineOptions({
  // 分享给朋友
  onShareAppMessage() {
    return {
      title: '灶搭子 - 智能菜谱推荐',
      path: '/pages/index/index',
      imageUrl: ''
    }
  },
  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '灶搭子 - 选择家里有的食材，我来帮您搭配菜谱~',
      path: '/pages/index/index',
      imageUrl: ''
    }
  }
})

// 在页面加载时初始化主题
onMounted(() => {
  initTheme();
});


  // 移除不适用的API调用
  // 动态设置状态栏文字颜色应该通过CSS样式控制，而不是通过API调用
</script>

<style scoped>
@import './index.scss';
</style>